from datetime import date, datetime
from google.appengine.api.urlfetch import fetch
from horseanalysis.lib.callable import Callable
from horseanalysis.lib.hkjc_fetcher.fetcher_base import FetcherBase
from horseanalysis.model.race import Race
import re

class ResultFetcher(FetcherBase):
  def getUrl(self):
    return "http://bet.hkjc.com/racing/pages/results.aspx?date=%(date_query)s&venue=%(venue)s&raceno=%(race_no)d&lang=en" % \
      {'date_query': self.date_query, 'venue': self.venue, 'race_no': self.race_no}
    
  def getData(self):
    data = fetch(self.getUrl())
    # data = fetch('http://localhost/hkjc-data/investment2.xml')
    return data.content
    
  def getResult(self):
    data = self.getData()
    
    # Check if it has data
    completed_pattern = re.compile("tableContent2")
    if completed_pattern.search(data):
      # Completed and ready to fetch
      race_result = ''
      for result in re.finditer(r"tableContent([0-9]*)\">([0-9]*)</td><td style=\"\" class=\"tableContent([0-9]*)\"><a href=\"javascript:goHorseRecord2", data):
        race_result += result.group(2) + ','
      if len(race_result) > 0:
        race_result = race_result[0:len(race_result) - 1]
      self.race.set_result(race_result)
    else:
      # Not completed
      pass
  
  def get_result_for_those_needed():
    races = Race.get_race_needed_for_result()
    for race in races:
      fetcher = ResultFetcher(race, '')
      fetcher.getResult()
    return races.count()
    
  get_result_for_those_needed = Callable(get_result_for_those_needed)